package com.example.hanqinshan.gifttalk.rank.item;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.hanqinshan.gifttalk.R;
import com.example.hanqinshan.gifttalk.entity.BaseEntity;
import com.example.hanqinshan.gifttalk.entity.RankItemData;
import com.example.hanqinshan.gifttalk.http.HttpManager;
import com.example.hanqinshan.gifttalk.widget.HeaderGridView;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/6/29.
 */
public class RankItemFragment extends Fragment {
    private static final String KEY_ID = "KEY_ID";
    private LayoutInflater mInflater;

    public static RankItemFragment newInstance (int id) {

        Bundle args = new Bundle();
        args.putInt(KEY_ID, id);
        RankItemFragment fragment = new RankItemFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private HeaderGridView mGridView;
    private RankGridAdapter mAdapter;
    private int id;

    @Nullable
    @Override
    public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mInflater = inflater;
        return inflater.inflate(R.layout.fragment_item_rank, container, false);
    }

    @Override
    public void onViewCreated (View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mGridView = (HeaderGridView) view.findViewById(R.id.grid_view);
    }

    @Override
    public void onActivityCreated (@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        id = getArguments().getInt(KEY_ID);
        mAdapter = new RankGridAdapter(getActivity());
        Call<BaseEntity<RankItemData>> callItems = HttpManager.getApi().getRankItems(id);
        callItems.enqueue(new Callback<BaseEntity<RankItemData>>() {
            @Override
            public void onResponse (Call<BaseEntity<RankItemData>> call, Response<BaseEntity<RankItemData>> response) {
                RankItemData data = response.body().getData();
                mAdapter.addAll(data.getItems());
                ImageView imageView = (ImageView) mInflater.inflate(R.layout.header_rank_grid, mGridView, false);
                Glide.with(RankItemFragment.this).load(data.getCover_image()).into(imageView);
                mGridView.addHeaderView(imageView);
                mGridView.setAdapter(mAdapter);
            }

            @Override
            public void onFailure (Call<BaseEntity<RankItemData>> call, Throwable t) {

            }
        });
    }
}
